package com.kotlin.myapplication.mvp.widget;

/**
 * Created by fan on 2017/8/27.
 */

import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Scroller;

public class SideslipListView extends ListView {
    private static final String TAG = "SideslipListAdapter";

    private int mScreenWidth;//屏幕的宽度
    private boolean isDeleteShow = false;//删除组件是否显示
    private ViewGroup mPointChild;//手指按下位置的item组件
    private int mDeleteWidth;//删除组件的宽度
    private LinearLayout.LayoutParams mItemLayoutParams;//手指按下时所在的item的布局参数
    private int mDownX;//手指初次按下的X坐标
    private int mDownY;//手指初次按下的Y坐标

    private int mPointPosition;//手指按下位置所在的item位置
    private boolean isAllowItemClick = true;//是否允许item点击
    private Scroller mScroller;
    private int mLastX = 0;
    private int mLastY = 0;
    private static final int TAN = 2;
    private boolean isHorizontalMove = true;//判断是否横滑
    int x = 0;
    int y = 0;
    private View view01;
    private View view02;
    private View viewParent;
    private boolean canSlip = false;

    public SideslipListView(Context context) {
        super(context);
        init(context);
    }

    public SideslipListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public SideslipListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        // 获取屏幕宽度
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        mScreenWidth = dm.widthPixels;
        Log.i(TAG, "***********mScreenWidth: " + mScreenWidth);
    }

    /* @Override
     public boolean onInterceptTouchEvent(MotionEvent ev) {//事件拦截
         switch (ev.getAction()) {
             case MotionEvent.ACTION_DOWN: {
                 x = (int) ev.getX();
                 y = (int) ev.getY();

                 isAllowItemClick = true;

                 //侧滑删除
                 mDownX = (int) ev.getX();
                 mDownY = (int) ev.getY();
                 mPointPosition = pointToPosition(mDownX, mDownY);
                 Log.i(TAG, "*******pointToPosition(mDownX, mDownY): " + mPointPosition);
                 if (mPointPosition != -1) {
                     if (isDeleteShow) {
                         ViewGroup tmpViewGroup = (ViewGroup) getChildAt(mPointPosition - getFirstVisiblePosition());
                         if (!mPointChild.equals(tmpViewGroup)) {
                             turnNormal();
                         }
                     }
                     //获取当前的item
                     mPointChild = (ViewGroup) getChildAt(mPointPosition - getFirstVisiblePosition());

                     mDeleteWidth = mPointChild.getChildAt(1).getLayoutParams().width;
                     mItemLayoutParams = (LinearLayout.LayoutParams) mPointChild.getChildAt(0).getLayoutParams();

                     Log.i(TAG, "*********mItemLayoutParams.height: " + mItemLayoutParams.height +
                             ", mDeleteWidth: " + mDeleteWidth);
                     mItemLayoutParams.width = mScreenWidth;
                     mPointChild.getChildAt(0).setLayoutParams(mItemLayoutParams);
                 }
                 break;
             }
             case MotionEvent.ACTION_MOVE: {
                 int nowX = (int) ev.getX();
                 int nowY = (int) ev.getY();
                 int diffX = nowX - mDownX;
                 Log.i(TAG, "******dp2px(4): " + dp2px(8) + ", dp2px(8): " + dp2px(8) +
                         ", density: " + getContext().getResources().getDisplayMetrics().density);
                 if (Math.abs(diffX) > dp2px(4) || Math.abs(nowY - mDownY) > dp2px(4)) {
                     return true;//避免子布局中有点击的控件时滑动无效
                 }
                 break;
             }
             case MotionEvent.ACTION_UP:
                 Log.d(TAG, x + "," + ev.getX());
                 if(Math.abs(ev.getX() - x) > 10){
                     isAllowItemClick = false;
                 }
                 break;
         }
         return super.onInterceptTouchEvent(ev);
     }*/

    public float dp2px(int dp) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getContext().getResources().getDisplayMetrics());
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {//事件响应
        if(canSlip) {
            switch (ev.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    performActionDown(ev);
                    break;
                case MotionEvent.ACTION_MOVE:
                    performActionMove(ev);
                    break;
                case MotionEvent.ACTION_UP:
                    performActionUp(ev);
                    break;
            }
        }
        return super.onTouchEvent(ev);
    }

    private void performActionDown(MotionEvent ev) {
        mDownX = (int) ev.getX();
        mDownY = (int) ev.getY();
        if (isDeleteShow) {
            ViewGroup tmpViewGroup = (ViewGroup) getChildAt(pointToPosition(mDownX, mDownY) - getFirstVisiblePosition());
            Log.i(TAG, "*********mPointChild.equals(tmpViewGroup): " + mPointChild.equals(tmpViewGroup));
            if (!mPointChild.equals(tmpViewGroup)) {
                turnNormal();
            }
        }
        //获取当前的item
        mPointChild = (ViewGroup) getChildAt(pointToPosition(mDownX, mDownY) - getFirstVisiblePosition());
        view01 = ((ViewGroup)mPointChild.getChildAt(0)).getChildAt(0);
        view02 = ((ViewGroup)mPointChild.getChildAt(0)).getChildAt(1);
        viewParent = (ViewGroup)mPointChild.getChildAt(0);

        mDeleteWidth = view02.getLayoutParams().width;//获取删除组件的宽度
        Log.i(TAG, "**********pointToPosition(x,y): " + pointToPosition(mDownX, mDownY)
                + ", getFirstVisiblePosition() = " + getFirstVisiblePosition()
                + ", mDeleteWidth = " + mDeleteWidth);
        mItemLayoutParams = (LinearLayout.LayoutParams) view01.getLayoutParams();

        mItemLayoutParams.width = mScreenWidth;
        view01.setLayoutParams(mItemLayoutParams);
    }

    private boolean performActionMove(MotionEvent ev) {
        int nowX = (int) ev.getX();
        int nowY = (int) ev.getY();
        int diffX = nowX - mDownX;
        //if (Math.abs(diffX) > Math.abs(nowY - mDownY) && Math.abs(nowY - mDownY) < 20) {
        if (!isDeleteShow && nowX < mDownX) {//删除按钮未显示时向左滑
            if (-diffX >= mDeleteWidth) {//如果滑动距离大于删除组件的宽度时进行偏移的最大处理
                diffX = -mDeleteWidth;
            }
            mItemLayoutParams.leftMargin = diffX;
            view01.setLayoutParams(mItemLayoutParams);
            isAllowItemClick = false;
        } else if (isDeleteShow && nowX > mDownX) {//删除按钮显示时向右滑
            if (diffX >= mDeleteWidth) {
                diffX = mDeleteWidth;
            }
            mItemLayoutParams.leftMargin = diffX - mDeleteWidth;
            view01.setLayoutParams(mItemLayoutParams);
            isAllowItemClick = false;
        }
        return true;
        //}
        //return super.onTouchEvent(ev);
    }

    private void performActionUp(MotionEvent ev) {
        if(Math.abs(mDownX - ev.getX()) > 10){
            isAllowItemClick = false;
        }else {
            isAllowItemClick = true;
        }
        Log.d(TAG, isDeleteShow() + "," + mDeleteWidth + "," + mItemLayoutParams.leftMargin);
        //如果向左滑出超过隐藏的二分之一就全部显示
        if (!isDeleteShow() && -mItemLayoutParams.leftMargin >= mDeleteWidth / 2) {
            mItemLayoutParams.leftMargin = -mDeleteWidth;
            isDeleteShow = true;
            view01.setLayoutParams(mItemLayoutParams);
        } else if(!isDeleteShow() && -mItemLayoutParams.leftMargin < mDeleteWidth / 2){
            turnNormal();
        } else if(isDeleteShow() && -mItemLayoutParams.leftMargin < mDeleteWidth / 2){
            turnNormal();
        }else{
            mItemLayoutParams.leftMargin = -mDeleteWidth;
            isDeleteShow = true;
            view01.setLayoutParams(mItemLayoutParams);
        }
    }

    /*
     * 转换为正常隐藏情况
     */
    public void turnNormal() {
        mItemLayoutParams.leftMargin = 0;
        if(null != mPointChild) {
            view01.setLayoutParams(mItemLayoutParams);
        }
        isDeleteShow = false;

    }

    /**
     * 是否允许Item点击
     *
     * @return
     */
    public boolean isAllowItemClick() {
        return isAllowItemClick;
    }

    public boolean isDeleteShow(){
        return isDeleteShow;
    }

    @Override
    /**
     * 重写该方法，达到使ListView适应ScrollView的效果
     */
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }

    public void setCanSlip(boolean canSlip){
        this.canSlip = canSlip;
    }
}